package com.mazaiting.blog.service

import com.mazaiting.blog.dao.VisitorDao
import com.mazaiting.blog.domain.Visitor
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.sql.Timestamp

/**
 *
 */
@Service
class VisitorService {

    /**日志框架*/
    val logger = LoggerFactory.getLogger(javaClass)!!
    /**
     * 访问者DAO
     */
    @Autowired
    lateinit var dao: VisitorDao
    /**
     * 保存访问者
     * @param visitor 访问者
     * @return true: 允许访问；false: 禁止访问
     */
    fun saveVisitor(visitor: Visitor) : Boolean {
        // 根据远程地址获取访问者
        val newVisitor = dao.selectByRemoteAddr(visitor.remoteAddr)
//        logger.info(newVisitor.toString())
        var isSuccess = true
        // 判断访问者是否为空
        // 如果为空则说明是第一次访问，则插入数据
        if (null == newVisitor) {
            // 插入数据
            val num = dao.addVisitor(visitor)
//            logger.info(num.toString())
            if (num < 1) isSuccess = false
        } else {
            // 更新数据
//            logger.info("更新数据")
            newVisitor.visitorNum += 1
            newVisitor.time = Timestamp(System.currentTimeMillis())
            val num = dao.updateVisitor(newVisitor)
//            logger.info(num.toString())
            if (num < 1) isSuccess = false
        }
        return isSuccess
    }

}